package pannel.user;

import system.BasePage;
import system.LoginRegisterPage;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.sql.SQLException;

public class PersonalPage extends BasePage {
    private JPanel infoPanel;
    private JLabel avatarLabel;
    private JLabel usernameLabel; // 改为JLabel
    private JLabel roleLabel;
    private UserDao userDao;

    public PersonalPage(User user) {
        super(user);
        userDao = new UserDao();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("个人信息");
        setupContent();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBackground(Color.WHITE);
        infoPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel card = createCardPanel();

        JPanel wrapperPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        wrapperPanel.setBackground(Color.WHITE);
        wrapperPanel.add(card);

        contentArea.add(wrapperPanel, BorderLayout.CENTER);
    }

    private JPanel createCardPanel() {
        JPanel card = new JPanel();
        card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
        card.setBackground(Color.WHITE);
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)
        ));
        card.setPreferredSize(new Dimension(500, 400));

        card.add(createAvatarPanel());
        card.add(Box.createVerticalStrut(20));
        card.add(createInfoPanel());
        card.add(Box.createVerticalStrut(20));
        card.add(createButtonPanel());

        return card;
    }

    private JPanel createInfoPanel() {
        JPanel infoPanel = new JPanel(new GridBagLayout());
        infoPanel.setBackground(Color.WHITE);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 用户ID
        gbc.gridx = 0;
        gbc.gridy = 0;
        infoPanel.add(new JLabel("用户ID:"), gbc);
        gbc.gridx = 1;
        infoPanel.add(new JLabel(String.valueOf(getCurrentUser().getId())), gbc);

        // 用户名（改为不可编辑的标签）
        gbc.gridx = 0;
        gbc.gridy = 1;
        infoPanel.add(new JLabel("用户名:"), gbc);

        usernameLabel = new JLabel(getCurrentUser().getUsername());
        gbc.gridx = 1;
        infoPanel.add(usernameLabel, gbc);

        // 角色
        gbc.gridx = 0;
        gbc.gridy = 2;
        infoPanel.add(new JLabel("角色:"), gbc);

        roleLabel = new JLabel(getCurrentUser().getRole());
        gbc.gridx = 1;
        infoPanel.add(roleLabel, gbc);

        return infoPanel;
    }

    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(Color.WHITE);

        // 只保留修改密码按钮
        JButton changePasswordButton = new JButton("修改密码");
        changePasswordButton.addActionListener(e -> handleChangePassword());
        buttonPanel.add(changePasswordButton);

        return buttonPanel;
    }

    // Avatar相关方法保持不变
    private JPanel createAvatarPanel() {
        JPanel avatarPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        avatarPanel.setBackground(Color.WHITE);

        avatarLabel = new JLabel();
        avatarLabel.setPreferredSize(new Dimension(100, 100));
        updateAvatarDisplay();

        JButton changeAvatarButton = new JButton("更换头像");
        changeAvatarButton.addActionListener(e -> handleAvatarChange());

        avatarPanel.add(avatarLabel);
        avatarPanel.add(changeAvatarButton);

        return avatarPanel;
    }

    private void updateAvatarDisplay() {
        if (getCurrentUser().getAvatarPath() != null && !getCurrentUser().getAvatarPath().isEmpty()) {
            try {
                ImageIcon originalIcon = new ImageIcon(getCurrentUser().getAvatarPath());
                Image image = originalIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
                avatarLabel.setIcon(new ImageIcon(image));
            } catch (Exception e) {
                avatarLabel.setText("头像加载失败");
            }
        } else {
            avatarLabel.setText("无头像");
        }
    }

    private void handleAvatarChange() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                String name = f.getName().toLowerCase();
                return f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".png")
                        || name.endsWith(".gif") || name.endsWith(".jpeg");
            }

            public String getDescription() {
                return "Image Files (*.jpg, *.png, *.gif, *.jpeg)";
            }
        });

        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                getCurrentUser().setAvatarPath(path);
                if (userDao.updateById(getCurrentUser())) {
                    updateAvatarDisplay();
                    JOptionPane.showMessageDialog(this, "头像更新成功！");
                } else {
                    JOptionPane.showMessageDialog(this, "头像更新失败！");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "头像更新失败：" + ex.getMessage());
            }
        }
    }

    private void handleChangePassword() {
        ChangePasswordDialog dialog = new ChangePasswordDialog(SwingUtilities.getWindowAncestor(this), getCurrentUser());
        if (dialog.showDialog()) {
            try {
                if (userDao.updatePassword(getCurrentUser().getId(), dialog.getOldPassword(), dialog.getNewPassword())) {
                    JOptionPane.showMessageDialog(this, "密码修改成功！请重新登录");
                    // 跳转到登录页面
                    SwingUtilities.getWindowAncestor(this).dispose();
                    new LoginRegisterPage().setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "旧密码验证失败！");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "密码修改失败：" + ex.getMessage());
            }
        }
    }
}class ChangePasswordDialog extends JDialog {
    private JPasswordField oldPasswordField;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;
    private boolean confirmed = false;
    private final User user;

    public ChangePasswordDialog(Window owner, User user) {
        super(owner, "修改密码", ModalityType.APPLICATION_MODAL);
        this.user = user;
        setupDialog();
    }

    private void setupDialog() {
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 旧密码
        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(new JLabel("旧密码:"), gbc);
        oldPasswordField = new JPasswordField(20);
        gbc.gridx = 1;
        mainPanel.add(oldPasswordField, gbc);

        // 新密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        mainPanel.add(new JLabel("新密码:"), gbc);
        newPasswordField = new JPasswordField(20);
        gbc.gridx = 1;
        mainPanel.add(newPasswordField, gbc);

        // 确认新密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        mainPanel.add(new JLabel("确认新密码:"), gbc);
        confirmPasswordField = new JPasswordField(20);
        gbc.gridx = 1;
        mainPanel.add(confirmPasswordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });
        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        setLayout(new BorderLayout());
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(getOwner());
        setResizable(false);
    }

    private boolean validateInput() {
        String oldPassword = new String(oldPasswordField.getPassword());
        String newPassword = new String(newPasswordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());

        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有密码字段都不能为空");
            return false;
        }

        if (!newPassword.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "新密码与确认密码不匹配");
            return false;
        }

        if (newPassword.equals(oldPassword)) {
            JOptionPane.showMessageDialog(this, "新密码不能与旧密码相同");
            return false;
        }

        return true;
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getOldPassword() {
        return new String(oldPasswordField.getPassword());
    }

    public String getNewPassword() {
        return new String(newPasswordField.getPassword());
    }
}